os module
In Python, the os module is a built-in module that allows a program to interact with the operating system. It helps you perform tasks like working with files and folders, getting system information, and managing directories. It is commonly used when a Python program needs to communicate with the computer's file system. OS module comes under Python's standard utility modules.
Some important functions of the Python os module are:Creating new folder
import os
os.mkdir("test_folder") # new folder 'test_folder' will be created in your current workind directory
os.rmdir("test_folder") # test_folder will be removed a folder
Getting the current working directory
import os
cwd = os.getcwd()
print("Current working directory: ", cwd)
Changing the directory
In certain cases, we may have to change the working directory and we can do so using os.chdir() method.
import os
cwd = os.getcwd()
print("Current working directory: ", cwd)
# chdir method will change directory. If your current working directory is d:/python/codes
os.chdir("C:/Users")
# os.chdir("C:/Users") command will change your directory to C:/Users
Listing files in a directory
import os
os.chdir("C:/movies")
os.listdir() # This command will display all the contents of movies directory stored in C drive
Checking if a file exists
If we want to know whether specific file exists in system or not, in that case we can use exists() method.
import os
if os.path.exists("digger.mp4"):
print("file exists")
else:
print("file does not exist")
Getting system information
We can know information about the Operating system of our system using, we can use os module. For example, os.name() returns name of os used.
import os
print("OS used in this machine: ",os.name)
Removing Directory
Suppose we have a folder named "hello" in our current working directory, we can remove folder hello using command: os.rmdir("hello")
import os
os.rmdir("hello")
print("files:",os.listdir())
Removing file
We can remove file using os.remove("filename") command.
import os
try:
if os.path.exists("hello.csv"): # this will check if a file exists or not
os.remove("hello.csv")
else:
print("file does not exists")
except IOError as e:
print("file error: ",e)
File Permissions
Python os module can be used to access and change file permissions. Some of the important methods for working with file permissions are:
import os
# Set read-write permissions of file sample.txt for owner (0o600)
os.chmod("hello.txt", 0o600)
# To change ownership and group id of file os.chown() method is used.
os.chown("hello.txt", 1000, 1000)
#To retrieve metadata about file os.stat() method is used.
stats = os.stat("hello.txt")
print("Size:", stats.st_size, "bytes")
print("Last modified:", stats.st_mtime)
print("Permissions:", oct(stats.st_mode)[-3:])